/**
 * 
 */
package com.dalonedrow.rpg.base.map;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;

/**
 * @author Donald
 *
 */
public class TileTerrain {
	/** a map of all instantiated TileTerrains. */
	private static HashMap<String, TileTerrain> map;
	/**
	 * Retrieves an existing TileTerrain by title.
	 * @param title the TileTerrain's title
	 * @return TileTerrain
	 * @throws IllegalArgumentException 
	 * if no TileTerrain with that title was instantiated
	 */
	public static TileTerrain valueOf(final String title)
	throws IllegalArgumentException {
		TileTerrain tt = TileTerrain.map.get(title);
		if (tt == null) {
			throw new IllegalArgumentException(
					"TileTerrain " + title + " not found!");
		}
		return tt;
	}
	/**
	 * Retrieves all TileTerrain instances created.
	 * @return TileTerrain[]
	 */
	public static TileTerrain[] values() {
		if (TileTerrain.map == null
				|| TileTerrain.map.isEmpty()) {
			return new TileTerrain[0];
		}
		Iterator<String> iter = TileTerrain.map.keySet().iterator();
		ArrayList<TileTerrain> list = new ArrayList<TileTerrain>();
		while (iter.hasNext()) {
			list.add(TileTerrain.map.get(iter.next()));
		}
		Collections.sort(list, new TileTerrainComparator());
		return list.toArray(new TileTerrain[list.size()]);
	}
	/** the TileTerrain's description. */
	private final String description;
	/** the TileTerrain's title. */
	private final String title;
	/**
	 * Creates a new instance of TileTerrain.java.
	 * @param newTitle the TileTerrain's title
	 * @param newDescription the TileTerrain's description
	 * @throws Exception if a TileTerrain with the same 
	 * title was already created
	 */
	public TileTerrain(final String newTitle, final String newDescription) 
	throws Exception {
		if (TileTerrain.map == null) {
			TileTerrain.map = new HashMap<String, TileTerrain>();
		}
		if (TileTerrain.map.containsKey(newTitle)) {
			throw new Exception("Terrain " + newTitle + " already created!");
		}
		title = newTitle;
		description = newDescription;
		TileTerrain.map.put(newTitle, this);
	}
	/**
	 * Gets the description.
	 * @return String
	 */
	public String getDescription() {
		return description;
	};
	/**
	 * Gets the title.
	 * @return String
	 */
	public String getTitle() {
		return title;
	}
	/**
	 * {@inheritDoc}
	 */
	@Override
	public String toString() {
		return title;
	}
	public int compareTo(final TileTerrain other) {
		return this.title.compareTo(other.title);
	}
}
/** Comparator for TileTerrain.java. */
class TileTerrainComparator implements Comparator<TileTerrain> {
	/**
	 * {@inheritDoc}
	 */
	public int compare(final TileTerrain terrain0, final TileTerrain terrain1) {
		return terrain0.getTitle().compareTo(terrain1.getTitle());
	}
}
